%% Copyright 2008 Kevin A. Smith 
%% Licensed under the Apache License, Version 2.0 (the "License"); 
%% you may not use this file except in compliance with the License. 
%% You may obtain a copy of the License at 
%%
%% http://www.apache.org/licenses/LICENSE-2.0 
%%
%% Unless required by applicable law or agreed to in writing, software 
%% distributed under the License is distributed on an "AS IS" BASIS, 
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
%% See the License for the specific language governing permissions and 
%% limitations under the License.

-module(aws_instance).

-export([run/3, run/5, terminate/2, terminate_set/2, describe_all/1, describe_set/2]).

describe_all(Keys) ->
	aws_util:send_request(Keys, [{"Action", ["DescribeInstances"]}], undefined).
	
describe_set(Keys, InstanceIds) ->
	aws_util:send_request(Keys, [{"Action", ["DescribeInstances"]}, {"InstanceId", InstanceIds}], undefined).

terminate_set(Keys, InstanceIds) ->
	aws_util:send_request(Keys, [{"Action", ["TerminateInstances"]}, {"InstanceId", InstanceIds}], terminate_instance_parser).

terminate(Keys, InstanceId) ->
	aws_util:send_request(Keys, [{"Action", ["TerminateInstances"]}, {"InstanceId", [InstanceId]}], terminate_instance_parser).

run(Keys, PubKeyName, ImageId) ->
    run(Keys, PubKeyName, ImageId, [], []).

run(Keys, PubKeyName, ImageId, UserData, InstanceType) when length(UserData) == 0, length(InstanceType) == 0 ->
	F = fun(R) -> file:write_file("output.xml", R) end,
    aws_util:send_request(Keys, [{"Action", ["RunInstances"]}, {"ImageId", [ImageId]}, {"MinCount", ["1"]},
						       {"MaxCount", ["1"]}, {"KeyName", [PubKeyName]}], run_instance_parser, F);

run(Keys, PubKeyName, ImageId, UserData, InstanceType) when length(UserData) > 0, length(InstanceType) == 0 ->
    aws_util:send_request(Keys, [{"Action", ["RunInstances"]}, {"ImageId", [ImageId]}, {"MinCount", ["1"]},
						       {"MaxCount", ["1"]}, {"UserData", [UserData]}, {"KeyName", [PubKeyName]}], run_instance_parser);

run(Keys, PubKeyName, ImageId, UserData, InstanceType) when length(UserData) == 0, length(InstanceType) > 0 ->
    aws_util:send_request(Keys, [{"Action", ["RunInstances"]}, {"ImageId", [ImageId]}, {"MinCount", [1]},
						       {"MaxCount", ["1"]}, {"InstanceType", [InstanceType]}, {"KeyName", [PubKeyName]}], run_instance_parser);

run(Keys, PubKeyName, ImageId, UserData, InstanceType) when length(UserData) > 0, length(InstanceType) > 0 ->
    aws_util:send_request(Keys, [{"Action", ["RunInstances"]}, {"ImageId", [ImageId]}, {"UserData", [UserData]},
						       {"InstanceType", [InstanceType]}, {"MinCount", ["1"]},
						       {"MaxCount", ["1"]}, {"KeyName", [PubKeyName]}], run_instance_parser).

